/*
** remove_from_serv.c for zappy in /home/guidet_m/TECK2/projets/zappy/server_zappy
** 
** Made by michael guidet
** Login   <guidet_m@epitech.net>
** 
** Started on  Mon Jul  4 15:35:36 2011 michael guidet
** Last update Mon Jul 11 10:12:24 2011 michael guidet
*/

#include "server.h"

void	clean_fd(t_env *e)
{
  t_fd	*tmp;
  t_fd	*next;

  tmp = e->fd;
  while (tmp)
    {
      next = tmp->next;
      if (tmp->type == DEAD)
	dead(tmp, e);
      if (tmp->type == DEAD || tmp->type == DECO)
	remove_from_fdlist(&e->fd, tmp);
      tmp = next;
    }
}

void	dead(t_fd *fd, t_env *env)
{
  char	cmd2[BUF_SIZE];
  t_fd	*tmp;

  printf("%sA drone from the team %s is dead%s\n", RED, fd->pl->team, DEFAUT);
  remove_drone_from_case(env->map, fd->pl->x, fd->pl->y, fd->pl);
  free(fd->pl);
  sprintf(cmd2, "pdi %d\n", fd->pl->id);
  for (tmp = env->fd; tmp; tmp = tmp->next)
    if (tmp->type == GRAPH)
      add_string_to_list(&tmp->send_list, cmd2);
  x_int(-1, send(fd->fd, "mort\n", 5, 0), "send");
}

void	remove_from_fdlist(t_fd **begin, t_fd *elem)
{
  t_fd	*tmp;
  char	*flush;
  int	i;

  close(elem->fd);
  for (i = 0; i < 10; i++)
    if (elem->action_list[i])
      free(elem->action_list[i]);
  flush = clean_string_list(&elem->receive_list);
  free(flush);
  flush = clean_string_list(&elem->send_list);
  free(flush);
  if (*begin == elem)
    {
      *begin = (*begin)->next;
      free(elem);
      return ;
    }
  for (tmp = *begin; tmp->next; tmp = tmp->next)
    if (tmp->next == elem)
      break;
  tmp->next = (tmp->next)->next;
  free(elem);
}
